package cn.itsource.exam.service.impl;

import cn.itsource.exam.domain.Permission;
import cn.itsource.exam.mapper.PermissionMapper;
import cn.itsource.exam.query.PermissionQueryVo;
import cn.itsource.exam.service.IPermissionService;
import cn.itsource.exam.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void deletePermission(Long PermissionId) {
        permissionMapper.delete(PermissionId);
    }

    @Override
    public void insertPermission(Permission Permission) {
        permissionMapper.insert(Permission);
    }

    @Override
    public void updatePermission(Permission Permission) {
        permissionMapper.update(Permission);
    }

    @Override
    public Permission selectPermissionByPermissionId(Long  PermissionId) {
        return permissionMapper.selectByPermissionId(PermissionId);
    }

    @Override
    public PageList<Permission> selectPermission(PermissionQueryVo PermissionQueryVo) {
        PageList<Permission> pageList=new PageList<Permission>();
        Integer total=permissionMapper.selectCount(PermissionQueryVo);
        if(total==null){
          return pageList;
        }
        List<Permission> Permissions = permissionMapper.selectPermissionList(PermissionQueryVo);
        pageList.setList(Permissions);
        pageList.setTotal(total);
        return  pageList;
    }

    @Override
    public Permission selectPermissionByName(Permission Permission) {
        if(Permission==null){
            return null;
        }
        return permissionMapper.selectByPermissionName(Permission.getName());
    }

    @Override
    public void batchDeletePermission(Long[] PermissionIds) {
        permissionMapper.batchDelete(PermissionIds);
    }

    @Override
    public Map<String ,Object> getAllPermissionsByRoleId(Long roleId) {
        Map<String ,Object> map =new HashMap<String ,Object>();
        List<Permission> rolePermissions=permissionMapper.selectRolePermissions(roleId);
        List<Permission> allPermissions=permissionMapper.selectAll();
        map.put("allPermissions",allPermissions);
        map.put("rolePermissions",rolePermissions);
        return map;
    }

    @Override
    public List<Permission> selectAllPermission() {
        return permissionMapper.selectAll();
    }

    @Override
    public void addRolePermission(Long rid, Long[] pids) {
        //先删除原有关系
        permissionMapper.RolePermission(rid);
        //保存新的关系
        permissionMapper.addRolePermission(rid,pids);
    }

    @Override
    public List<Permission> getPermissionByUserId(String id) {
        return permissionMapper.getPermissionByUserId(id);
    }
}
